package com.ews.onlineexchange.service.observer;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.ejb.Asynchronous;
import javax.ejb.Stateless;
import javax.enterprise.event.Observes;
import javax.enterprise.event.TransactionPhase;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import javax.transaction.Transactional.TxType;
import javax.websocket.DeploymentException;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.TradeStatus;
import com.ews.onlineexchange.service.NotificationService;
import com.ews.onlineexchange.service.SmsService;
import com.ews.onlineexchange.service.TradeService;
import com.ews.onlineexchange.service.qualifier.BulletinAgreeEvent;
import com.ews.onlineexchange.service.test.BulletinEndClientEndPointService;

@Stateless
public class BulletinAgreeObserver {
	
	@Inject
	SmsService smsService;
	@Inject
	TradeService tradeService;
	
	@Inject
	NotificationService  notificationService;
	@Inject
	EntityManager entityManager;
	@Inject
	BulletinEndClientEndPointService bulletinEndClientEndPointService;
	
	@Asynchronous
	@Transactional( value = TxType.REQUIRED )
	public void listenBulletinAudit(@Observes(during = TransactionPhase.AFTER_SUCCESS)  @BulletinAgreeEvent Bulletin bulletin) throws DeploymentException, IOException, URISyntaxException {
		bulletin = entityManager.find(Bulletin.class, bulletin.getId());
		System.out.println(bulletin.getTradeStatus());
		if (bulletin.getTradeStatus().equals(TradeStatus.Agreed)) {
			try {
				smsService.addWinMessageToSupplier(bulletin);
				smsService.addOverMessageToBuyer(bulletin);
				notificationService.sendFailNotification(bulletin);
				notificationService.sendSuccessNotification(bulletin);
//				if(!bulletin.getWayOfChoose().equals(ChooseType.Manual)) {
//					bulletinEndClientEndPointService.sendMessage(bulletin);
//				}		
				tradeService.invalidateConflictingTrades( bulletin );
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}
	
}
